﻿using System;
using System.Drawing;
using System.IO;
using CosyTrade.Organization;
using CosyTrade.UI;
using CosyTrade.Futures;
using CosyTrade.Data;
using CosyTrade.Store;
using System.Collections.Generic;
using DevExpress.XtraEditors.Controls;
using NHibernate.Expression;
using System.Windows.Forms;

namespace CosyTrade.ClientForm.Futues
{
    public partial class FuturesOrderDetail : DetailFormBase
    {
        private FuturesOrder GetCurrentOrder = null;
        public bool canEdit=true;

        public FuturesOrderDetail():this(Guid.Empty)
        {}
        public FuturesOrderDetail( Guid extKey) : base(extKey)
        {
            InitializeComponent();
            LoadCompanys();
            //GetCurrentOrder = CurrentObject as FuturesOrder;
        }

        void LoadCompanys()
        {
            IList<Company> companies = Operation.OrganizationSystem.GetCompanyList();
            foreach (Company company in companies)
                cmbOrderArea.Properties.Items.Add(new ImageComboBoxItem(company.Caption, company));
        }

        protected override void DataBinding()
        {
            if (GetCurrentOrder == null) GetCurrentOrder = CurrentObject as FuturesOrder;
            if (CurrentStat != DetailFormCurrentStat.AddStat)
                radPaymethod.Enabled = false;
            else
                GetCurrentOrder.OrderId = GetNextOrderid();
            BindingControl(txtOrderId,"EditValue","OrderId");
            BindingControl(txtClientName, "EditValue", "ClientName");
            BindingControl(txtTotalValues, "EditValue", "TotalValues");
            BindingControl(txtWaresCount, "EditValue", "WaresCount");
            BindingControl(txtContextType,"EditValue", "ContextType");
            BindingControl(txtDelayPercent,"EditValue","DelayPercent");
            BindingControl(txtDeliverGoodAddress, "EditValue", "DeliverGoodAddress");
            BindingControl(txtFavorable,"EditValue","Favorable");
            BindingControl(datePayLimitDate, "EditValue", "PayLimitDate");
            BindingControl(dateBuildDate,"EditValue","BuildDate");
            BindingControl(cmbOrderArea, "EditValue", "OrderArea");
            BindingControl(popBuildEmp,"EditValue","BuildEmp");
            BindingControl(radHasFavorable, "EditValue", "HasFavorable");

            if (GetCurrentOrder != null)
            {
                InitList(GetCurrentOrder);
                radPaymethod.EditValue = (int)GetCurrentOrder.PMethod;
                if (GetCurrentOrder.OrderPayInfos.Count > 0)
                {
                    PayInfo info = GetCurrentOrder.OrderPayInfos[0];
                    txtPayer.EditValue = info.Payer;
                    BindingControl(datePayDate, "EditValue", "PayDate");
                }
            }
        }

        void InitList(FuturesOrder order)
        {

            bindingSource1.DataSource = order.DelayPayInfo;
            bindingSource3.DataSource = order.OrderWares;
            bindingSource4.DataSource = order.OrderPayInfos;
        }

        protected override BusinessObject InitBusinessObject(Guid currObjKey)
        {
            return Operation.FuturesMgr.GetFuturesOrder(currObjKey);
        }

        protected override BusinessObject CreateNewBusinessObject()
        {
            return new FuturesOrder();
        }

        protected override string GetTitle()
        {
            return "编辑期货订单";
        }

        protected override bool IsVail()
        {
            
            return true;
        }

        protected override DetailFormCurrentStat GetDefaultStat()
        {
            return DetailFormCurrentStat.ViewStat;
        }

        protected override void Save(BusinessObject currentObj)
        {
            if (!canEdit)
            {
                Functions.ShowConfigBox("该订单已不能修改");
                return;
            }
            if (!(currentObj is FuturesOrder)) return;
            if(GetCurrentOrder==null) GetCurrentOrder = currentObj as FuturesOrder;

            if (CurrentStat == DetailFormCurrentStat.AddStat)
            {
                PayInfo info = new PayInfo();
                info.Paystate = true;
                
                double dd;
                

                info.OrderGuid = GetCurrentOrder.PrimaryKey;
                info.Payer = txtPayer.Text;
                info.GetPayer = txtGetter.Text;

                int t = (int) radPaymethod.EditValue;
                switch (t)
                {
                    case 0:
                        info.PayDate = DateTime.Now;
                        info.Paymethod = PayMethod.Cash;
                        double.TryParse(txtMoney.Text, out dd);
                        info.Money = dd;
                        GetCurrentOrder.PMethod = PayMethod.Cash;
                        break;
                    case 1:
                        info.PayDate = datePayDate.DateTime;
                        info.Paymethod = PayMethod.Cheque;
                        double.TryParse(txtMoney1.Text, out dd);
                        info.Money = dd;
                        info.PayCode = txtPayCode.Text;
                        GetCurrentOrder.PMethod = PayMethod.Cheque;
                        GetCurrentOrder.OrderPayInfos.Add(info);
                        break;
                    default:
                        GetCurrentOrder.PMethod = PayMethod.Payable;
                        break;
                }
                //if (bindingSource4.DataSource != null)
                //{
                //    IList<PayInfo> payInfos = bindingSource4.DataSource as IList<PayInfo>;
                //    if (payInfos != null)
                //        foreach (PayInfo payInfo in payInfos)
                //            GetCurrentOrder.OrderPayInfos.Add(payInfo);
                //}
                //if (bindingSource3.DataSource != null)
                //{
                //    IList<OrderFormWares> wareses = bindingSource3.DataSource as IList<OrderFormWares>;
                //    if (wareses != null)
                //        foreach (OrderFormWares ware in wareses)
                //            GetCurrentOrder.OrderWares.Add(ware);
                //}
            }
            if (CurrentStat == DetailFormCurrentStat.AddStat) GetCurrentOrder.OrderId = GetNextOrderid();
            switch (CurrentStat)
            {
                case DetailFormCurrentStat.AddStat:
                    Operation.FuturesMgr.CreateFuturesOrder(GetCurrentOrder);
                    break;
                case DetailFormCurrentStat.EditStat:
                    Operation.FuturesMgr.UpdateOrderAndItChilds(GetCurrentOrder);
                    break;
                default:
                    break;
            }
        }

        void SetPayMedthod(int type)
        {
            switch (type)
            {
                case 0:
                    panelCash.Visible = true;
                    panelPayable.Visible = panelCheque.Visible = false;
                    //CreatePayinfo(1);
                    break;
                case 1:
                    panelCheque.Visible = true;
                    panelPayable.Visible = panelCash.Visible = false;
                    //CreatePayinfo(1);
                    break;
                case 2:
                    panelPayable.Visible = true;
                    panelCash.Visible = panelCheque.Visible = false;
                    //CreatePayinfo((int) txtPayRow.EditValue);
                    break;
            }
        }

        private void dateEdit3_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void selectEmployee1_OnSelected(object sender, EventArgs e)
        {
            popBuildEmp.EditValue = selectEmployee1.GetSelectedEmployee;

            if (popupContainerControl1.OwnerEdit != null)
                popBuildEmp.ClosePopup();

        }

        private void popEmployee_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
        {
            if (e.Value == null)
                e.DisplayText = "未指定";
            else
            {
                Employee employee = e.Value as Employee;
                e.DisplayText = employee != null ? employee.EmpName : "未指定";
            }
        }

        private void radPaymethod_SelectedIndexChanged(object sender, EventArgs e)
        {
            SetPayMedthod((int) radPaymethod.EditValue);
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            SearchProduct();
        }

        void SearchProduct()
        {
            IList<Product> sources = Operation.FuturesMgr.GetProductList(Expression.Or(Expression.Like("ProductCode", txtKeyword.Text.Trim(), MatchMode.Anywhere), Expression.Or(Expression.Like("CaptionSpaish", txtKeyword.Text.Trim(), MatchMode.Anywhere), Expression.Like("CaptionChinese", txtKeyword.Text.Trim(), MatchMode.Anywhere))));
            bindingSource2.DataSource = sources;
        }

        private void labelControl35_Click(object sender, EventArgs e)
        {

        }

        private void txtKeyword_KeyUp(object sender, KeyEventArgs e)
        {
            if(e.KeyValue==13)
            {
                //new Thread(SearchProduct).Start();
                SearchProduct();
            }
        }

        private void labelControl36_Click(object sender, EventArgs e)
        {

        }

        private void gridProduct_KeyDown(object sender, KeyEventArgs e)
        {
            
        }

        private void gridProduct_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Clicks == 1 && e.Button == MouseButtons.Left)
            {
                btnEditW.Visible = false;
                btnAddW.Visible = true;
                Product product = bindingSource2.Current as Product;
                SetCurrentProduct(product);
            }
        }

        private void gridWares_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Clicks == 1 && e.Button == MouseButtons.Right)
                popupMenu2.ShowPopup(gridWares.PointToScreen(e.Location));
            else if(e.Clicks == 1 && e.Button == MouseButtons.Left)
            {
                btnEditW.Visible = true;
                btnAddW.Visible = false;
                if (bindingSource3.Current != null)
                {
                    OrderFormWares ware = bindingSource3.Current as OrderFormWares;
                    if (ware != null)
                    {
                        txtBoxCount.EditValue = ware.BoxCount;
                        txtEveryBoxCount.EditValue = ware.EveryBoxCount;
                        txtFavorable1.EditValue = ware.Favorable;
                        txtOrderPrice.EditValue = ware.OrderPrice;
                        chkHasFavorable.Checked = ware.HasFavorable;
                        
                        SetCurrentProduct(ware.MapWare);
                    }
                }
            }
        }

        private void gridDelaypay_MouseDown(object sender,MouseEventArgs e)
        {
            if (e.Clicks == 1 && e.Button == MouseButtons.Right)
                popupMenu1.ShowPopup(gridDelaypay.PointToScreen(e.Location));
        }

        private void gridPayable_MouseDown(object sender,MouseEventArgs e)
        {
            if (e.Clicks == 1 && e.Button == MouseButtons.Right)
                popupMenu3.ShowPopup(gridPayable.PointToScreen(e.Location));
        }

        string GetNextOrderid()
        {
            DateTime dts = new DateTime(DateTime.Now.Year, 1, 1);
            DateTime dte = new DateTime(DateTime.Now.Year, 12, 31);

            ICriterion criterion = Expression.Like("OrderId", "No" + DateTime.Now.Month + ":%");
            criterion = Expression.And(criterion, Expression.Between("BuildDate", dts, dte));

            int num =Operation.FuturesMgr.GetFuturesOrders(criterion).Count;

            if (num < 10) return "No" + DateTime.Now.Month + ":000" + (num + 1);
            if (num >= 10 && num <= 99) return "No" + DateTime.Now.Month + ":00" + (num + 1);
            if (num >= 100 && num <= 999) return "No" + DateTime.Now.Month + ":0" + (num + 1);
            return "No" + DateTime.Now.Month + ":" + num;
        }

        //void CreatePayinfo(int row)
        //{
        //    if (GetCurrentOrder != null)
        //    {
        //        int max = row - GetCurrentOrder.OrderPayInfos.Count;
        //        if (max <= 0) return;
        //        for (int i = 0; i <= max; i++)
        //            GetCurrentOrder.OrderPayInfos.Add(new PayInfo());
        //    }
        //}

        //private IList<OrderFormWares> wares = new List<OrderFormWares>();
        //private IList<PayInfo> payinfolist = new List<PayInfo>();
        //private IList<DelayPay> delaypaylist = new List<DelayPay>();

        void DeletePayinfo()
        {
            if(bindingSource4.Current!=null)
            {
                PayInfo info = bindingSource4.Current as PayInfo;
                if (info != null && Functions.ShowConfigBox("您确定要删除当前所选的付款记录吗？") == DialogResult.Yes)
                {
                    Operation.FuturesMgr.DeletePayinfo(info.PrimaryKey);
                    FuturesOrder order = CurrentObject as FuturesOrder;
                    PayInfo temp = null;
                    foreach (PayInfo payInfo in order.OrderPayInfos)
                    {
                        if (payInfo.PrimaryKey == info.PrimaryKey) {
                            temp = payInfo;
                            break;}
                    }
                    if (temp != null)
                    {
                        order.OrderPayInfos.Remove(temp);
                        Operation.FuturesMgr.DeletePayinfo(temp.PrimaryKey);
                        Operation.FuturesMgr.UpdateFuturesOrder(order);
                        bindingSource4.RemoveCurrent();
                    }
                }
            }
        }

        void DeleteDelayinfo()
        {
            if(bindingSource1.Current != null)
            {
                DelayPay pay = bindingSource1.Current as DelayPay;
                if(pay!=null && Functions.ShowConfigBox("您确定要删除当前所选的付款记录吗？") == DialogResult.Yes)
                {
                    Operation.FuturesMgr.DeleteDelayinfo(pay.PrimaryKey);
                    FuturesOrder order = CurrentObject as FuturesOrder;
                    DelayPay temp = null;
                    if (order != null)
                    {
                        foreach (DelayPay payInfo in order.DelayPayInfo)
                        {
                            if (payInfo.PrimaryKey == pay.PrimaryKey)
                            {
                                temp = payInfo;
                                break;
                            }
                        }
                        if (temp != null)
                        {
                            order.DelayPayInfo.Remove(temp);
                            Operation.FuturesMgr.DeleteDelayinfo(temp.PrimaryKey);
                            Operation.FuturesMgr.UpdateFuturesOrder(order);
                            bindingSource1.RemoveCurrent();
                        }
                    }
                }
            }
        }

        void DeleteOrderWares()
        {
            if (bindingSource3.Current != null)
            {
                OrderFormWares ware = bindingSource3.DataSource as OrderFormWares;
                if(ware!=null&&  Functions.ShowConfigBox("您确定要删除当前所选的付款记录吗？") == DialogResult.Yes)
                {
                    Operation.FuturesMgr.DeleteOrderWares(ware.PrimaryKey);
                    FuturesOrder order = CurrentObject as FuturesOrder;
                    OrderFormWares temp = null;
                    foreach (OrderFormWares owares in order.OrderWares)
                    {
                        if (owares.PrimaryKey == ware.PrimaryKey)
                        {
                            temp = owares;
                            break;
                        }
                    }
                    if (temp != null)
                    {
                        order.OrderWares.Remove(temp);
                        Operation.FuturesMgr.DeleteOrderWares(temp.PrimaryKey);
                        Operation.FuturesMgr.UpdateFuturesOrder(order);
                        bindingSource3.RemoveCurrent();
                    }
                }
            }
        }

        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DeleteDelayinfo();
        }

        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DeleteOrderWares();
        }

        private void barButtonItem3_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DeletePayinfo();
        }

        private void repositoryItemTextEdit1_CustomDisplayText(object sender, CustomDisplayTextEventArgs e)
        {
            if (e.Value != null)
            {
                ProductCategory category = e.Value as ProductCategory;
                e.DisplayText = category != null ? category.CategoryChinese + "(" + category.CategorySpanish + ")" : "";
            }
        }

        private void repositoryItemTextEdit2_CustomDisplayText(object sender, CustomDisplayTextEventArgs e)
        {
            if(e.Value!=null)
            {
                Product product = e.Value as Product;
                e.DisplayText =product!=null?product.Caption:"";
            }
        }

        private void textEdit2_EditValueChanged(object sender, EventArgs e)
        {

        }

        void SetCurrentProduct(Product product)
        {
            if (product != null)
            {
                labChina.Text = "中文名称：" + product.CaptionChinese;
                labEnglish.Text = "西文名称：" + product.CaptionSpaish;
                labProcode.Text = "商品编号：" + product.ProductCode;
                labMetial.Text = "材料质地：" + product.Material;
                labWeight.Text = "毛重：" + product.GrossWeight;
                labModule.Text = "规格型号：" + product.ModuleInfo;
                labStoreCount.Text = "库存：10";
                labMemoc.Text = product.Memo;
                labFactory.Text = product.FactoryModule;
                labBarcode.Text = "条形码："+product.BarCode;

                byte[] imgData = Operation.DataStorage.GetData(product.ImagePath);
                if (imgData != null)
                    picProduct.Image = new Bitmap(new MemoryStream(imgData));
                //picProduct.Image = System.Drawing.Image.FromFile(product.ImagePath);
            }
        }

        private void txtPayRow_EditValueChanged(object sender, EventArgs e)
        {
            //CreatePayinfo((int)txtPayRow.EditValue);
        }

        private void simpleButton3_Click(object sender, EventArgs e)
        {
            OrderFormWares ware = new OrderFormWares();
            if(bindingSource2.Current!=null)
            {
                Product product = bindingSource2.Current as Product;
                ware.MapWare = product;
                double d = 0;
                double.TryParse(txtOrderPrice.Text, out d);
                ware.OrderPrice = d;
                
                double.TryParse(txtBoxCount.Text, out d);
                ware.BoxCount = d;
                double.TryParse(txtEveryBoxCount.Text, out d);
                ware.EveryBoxCount = d;

                ware.TotalCount = ware.BoxCount*ware.EveryBoxCount;
                ware.TotalPrice = ware.TotalCount*ware.OrderPrice;
                ware.HasFavorable = chkHasFavorable.Checked;
                
                if(ware.HasFavorable)
                {
                    double dd;
                    double.TryParse(txtFavorable1.Text, out dd);
                    ware.Favorable = dd;
                    ware.FavorableValue = ware.TotalPrice*(ware.Favorable/100.00f);
                }

                if (GetCurrentOrder != null)
                    GetCurrentOrder.OrderWares.Add(ware);
                gridWares.RefreshDataSource();
                ResetWaresItem();
            }
        }

        private void simpleButton4_Click(object sender, EventArgs e)
        {
            UpdateCurrentObj();
        }

        void UpdateCurrentObj()
        {
             if(GetCurrentOrder!=null)
             {
                 if(bindingSource3.Current!=null)
                 {
                     OrderFormWares ware = bindingSource3.Current as OrderFormWares;
                     double dd;
                     double.TryParse(txtOrderPrice.Text, out dd);
                     ware.OrderPrice = dd;
                     double.TryParse(txtBoxCount.Text, out dd);
                     ware.BoxCount = dd;
                     double.TryParse(txtEveryBoxCount.Text, out dd);
                     ware.EveryBoxCount = dd;
                     ware.HasFavorable = chkHasFavorable.Checked;
                     double.TryParse(txtFavorable1.Text, out dd);
                     ware.Favorable = dd;
                 }

                 GetCurrentOrder.TotalValues = 0;
                 GetCurrentOrder.WaresCount = 0;
                 foreach (OrderFormWares item in GetCurrentOrder.OrderWares)
                 {
                     GetCurrentOrder.TotalValues += item.HasFavorable ? item.FavorableValue : item.TotalPrice;
                     GetCurrentOrder.WaresCount += (int)item.TotalCount;

                 }
                 if (GetCurrentOrder.HasFavorable)
                     GetCurrentOrder.FavorableValue = GetCurrentOrder.TotalValues*(GetCurrentOrder.Favorable/100.00f);
                 gridWares.RefreshDataSource();
                 ResetWaresItem();
             }
            
        }

        void ResetWaresItem()
        {
            txtOrderPrice.Text = "0.00";
            txtBoxCount.Text = "0.00";
            txtEveryBoxCount.Text = "0.00";
            txtFavorable1.Text = "0.00";
            chkHasFavorable.Checked = false;
        }

        private void labelControl40_Click(object sender, EventArgs e)
        {

        }

        private void checkEdit1_CheckedChanged(object sender, EventArgs e)
        {
            txtFavorable1.Properties.ReadOnly = !chkHasFavorable.Checked;
        }

        private void bindingSource3_PositionChanged(object sender, EventArgs e)
        {

        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            if(string.IsNullOrEmpty(txtPayer.Text)||string.IsNullOrEmpty(txtGetter.Text))
            {
                Functions.ShowMessageBox("请输入付款人姓名和收款人姓名");
                return;
            }
            PayInfo info = new PayInfo();
            info.Paystate = chkPaystate.Checked;
            info.Paymethod = PayMethod.Payable;
            info.PayDate = datePaydate1.DateTime;
            double dd;
            double.TryParse(txtMoney2.Text, out dd);
            info.Money = dd;
            info.OrderGuid = GetCurrentOrder.PrimaryKey;
            info.Payer = txtPayer.Text;
            info.GetPayer = txtGetter.Text;
            info.PayCode = "";
            GetCurrentOrder.OrderPayInfos.Add(info);
            gridPayable.RefreshDataSource();

            txtMoney2.Text ="0.00";
            txtPayer.Text = "";
            txtGetter.Text = "";
        }

        private void radHasFavorable_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtFavorable.Visible = labelControl12.Visible = labelControl10.Visible = (bool) radHasFavorable.EditValue;
        }

        //private void dateEdit1_EditValueChanged(object sender, EventArgs e)
        //{

        //}

    }
}
